# Local Variable
CC := g++
TARGET := my_app
TOP_DIR := $(shell pwd)
STATIC_LIB_OUTPUT_DIR := $(shell pwd)/lib
TARGET_OUTPUT_DIR := $(shell pwd)/bin
TARGET_INCLUDE_DIR := $(shell pwd)/include
# Compilation of the util directory before compiling this directory(including my_app, cfg and MyDB)
SUB_DIRS := $(TOP_DIR)/utils $(TOP_DIR)/src
MYSQL_LIB := `mysql_config --cflags --libs`

# 编译的时候使用的选项。-Wall 表示输出警告信息。
CXFLAGS = -std=c++11 -g -Wall -fmessage-length=0
# 链接库时使用的选项
LDFLAGS = -lpthread

# Below two variables are long string rather than array.
# INCLUDE = -I ./include -I ./include/mymath
INCLUDE = -I $(TOP_DIR)/include
LIB = -L $(TOP_DIR)/lib

# 使在这个目录里面定义的变量可以在被调用的下级 makefile 中使用。To be Global Variable
export CC TARGET STATIC_LIB_OUTPUT_DIR TARGET_OUTPUT_DIR TARGET_INCLUDE_DIR CXFLAGS LDFLAGS INCLUDE LIB MYSQL_LIB

.PHONY : all

# all的依赖，如此这般，处理顺序为：clean>CHECKDIR>init>all [utils>src]
all : clean CHECKDIR init
	@list='$(SUB_DIRS)';for subdir in $$list; do \
		cd $$subdir && make; \
	done

# 创建用于放置静态库的文件夹
CHECKDIR:
	mkdir -p $(STATIC_LIB_OUTPUT_DIR) $(TARGET_OUTPUT_DIR) $(TARGET_INCLUDE_DIR)

# 用于清理上所有次打包后的文件,后续子makefile就不需要执行clean命令。子makefile只需要专注编译即可
clean :
	@echo '--- [Start] clean all of old files ---'
	rm -rf $(STATIC_LIB_OUTPUT_DIR)
	rm -rf $(TARGET_OUTPUT_DIR)
	rm -rf $(TARGET_INCLUDE_DIR)
	find $(TOP_DIR) -type f -name $(TARGET) | xargs rm -f
	find . -type f -name *.o | xargs rm -f
	@echo '---  [End]  clean all of old files ---'

init :
	cd $(TOP_DIR) && cp *.conf $(TARGET_OUTPUT_DIR)

